<template>
  <div class="account">
    <el-form :model="form" :rules="rules" ref="ruleFormRef">
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormRules, ElForm } from 'element-plus'
import { accountLoginRequest } from '@/service/login'
import useLoginStore from '@/store/login/index'
import { localCache } from '@/utils/cache'

const form = reactive({
  account: localCache.getCache('name') ?? '',
  password: localCache.getCache('password') ?? '',
})

const rules: FormRules = {
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码 ', trigger: 'blur' }],
}

const ruleFormRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()
const LoginAction = (keepPassword: boolean) => {
  ruleFormRef?.value?.validate((valid) => {
    if (valid) {
      const username = form.account
      const password = form.password
      loginStore.loginAccountAction({ username, password }).then((res) => {
        if (keepPassword) {
          localCache.setCache('name', username)
          localCache.setCache('password', password)
        } else {
          localCache.removeCache('name')
          localCache.removeCache('password')
        }
      })
    } else {
      ElMessage({
        message: '请输入账号密码',
        type: 'warning',
      })
    }
  })
}

defineExpose({
  LoginAction,
})
</script>

<style scoped>
.account {
}
</style>
